package com.jintoufs.interceptor;

import com.jintoufs.domain.constants.MessageConstants;

import com.jintoufs.util.valid.ValidUtil;
import net.sf.json.JSONObject;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;

/**
 * @author pengyang
 * Created by yangpeng on 2017/11/2.
 */
public class ParamNotEmptyIntercepter extends BaseInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
        AjaxMsg ajaxMsg = new AjaxMsg();
        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            //获取方法上的注解
            ParamCheck paramCheck = ((HandlerMethod) handler).getMethodAnnotation(ParamCheck.class);
            //判断判断该方法是否需要参数校验,如不需要验证则返回true
            if (paramCheck == null || "".equals(paramCheck.params())) {
                return  true;
            }else{
                String[] paramsName = paramCheck.params().split(",");
                ArrayList params = new ArrayList();
                for (String s : paramsName) {
                    params.add(req.getParameter(s));
                }
                if (ValidUtil.isEmpty(params.toArray())) {
                    ajaxMsg.setCode(AjaxMsg.FAILURE);
                    ajaxMsg.setMessage(MessageConstants.PARAM_CHECK_ERROR_MESSAGE);
                    JSONObject jsonObject = JSONObject.fromObject(ajaxMsg);
                    res.setContentType("text/html;charset=utf8");
                    res.getWriter().print(jsonObject.toString());
                    return false;
                }else{
                    return true;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
